package com.woniuxy.gateway;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Order(2)
public class AdminFilter implements GlobalFilter {
    @Autowired
    private AuthenUrlsProperties urls;
    private AntPathMatcher matcher =new AntPathMatcher();

    public boolean isUserUrl(String url) {
        for (String userUrl : urls.getUserUrls()) {
            if (matcher.match(userUrl, url)) return true;
        }
        return false;
    }

    public boolean isBaseUrl(String url) {
        for (String baseUrl : urls.getBaseUrls()) {
            if (matcher.match(baseUrl, url)) return true;
        }
        return false;
    }

    public boolean isAdminUrl(String url) {
        for (String adminUrl : urls.getAdminUrls()) {
            if (matcher.match(adminUrl, url)) return true;
        }
        return false;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        List<String> userUrls = urls.getUserUrls();

        String url = exchange.getRequest().getURI().toString();
        System.out.println(url + "$$$123");
        if (!url.endsWith(".api")) return chain.filter(exchange);
        System.out.println("管理员认证登录状态");

        if (isAdminUrl(url) || isBaseUrl(url))
            return chain.filter(exchange);
        //进行验证
        List<String> admin_token = exchange.getRequest().getHeaders().get("admin_token");

        return chain.filter(exchange);
    }
}
